import 'dart:convert';
// import 'dart:html';
// import 'dart:html';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:info_ca/bean/hostModel.dart';
import 'package:info_ca/bean/userModel.dart';

class ArticleDetailPage extends StatefulWidget {
  const ArticleDetailPage({super.key});

  @override
  State<ArticleDetailPage> createState() => _ArticleDetailPageState();
}

class _ArticleDetailPageState extends State<ArticleDetailPage> {
  final TextEditingController _controller = TextEditingController();

  String host = HostModel.ipHost;
  int articleId = 0;
  List commentList = [];
  String userName = "";
  String title = "";
  String articleContext = "";
  String belong = "";
  int userId = 0;
  @override
  Widget build(BuildContext context) {
    final Map<String, dynamic> args =
        ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>;
    articleId = args['articleId'];

    return Scaffold(
      body: Container(
        // height: ,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Container(
              height: MediaQuery.of(context).size.height * 0.9,
              child: ListView(children: [
                buildAppBar(),
                buildUserInfoBody(),
                buildImgList(),
                buildCommentList(),
              ]),
            ),
          ],
        ),
      ),
      resizeToAvoidBottomInset: false,
      bottomNavigationBar: SafeArea(child: buildBottomComment(),),
    );
  }

  void ShowDialog(String res) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('获取失败'),
        content: Text(res),
        actions: <Widget>[
          TextButton(
            child: const Text('OK'),
            onPressed: () {
              Navigator.popUntil(context, ModalRoute.withName('/home'));
            },
          )
        ],
      ),
    );
  }

  Future<void> getData() async {
    try {
      final response = await http
          .get(
            Uri.parse("http://$host/view/searchArticle?ArticleId=$articleId"),
          )
          .timeout(const Duration(seconds: 30));
      if (response.statusCode == 200) {
        final Map<String, dynamic> articlelDetail =
            json.decode(response.body)['result'];
        if (json.decode(response.body)["code"] == 200) {
          userId = articlelDetail["user_id"];
          userName = articlelDetail["user_name"];
          title = articlelDetail["title"];
          articleContext = articlelDetail["article_context"];
          belong = articlelDetail["belong"];
        } else {
          ShowDialog(json.decode(response.body)['res']);
        }
      }
      final Comment = await http.get(
        Uri.parse(
            "http://$host/view/commentListLim?ArticleId=$articleId&Offset=1"),
        headers: {
          'Authorization': 'Bearer',
        },
      ).timeout(const Duration(seconds: 30));
      if (Comment.statusCode == 200) {
        if (json.decode(response.body)['code'] == 200) {
          commentList = json.decode(Comment.body)['result']['list'];
          setState(() {});
        } else {
          ShowDialog(json.decode(Comment.body)['res']);
        }
      }
    } catch (e) {
      print(e);
      throw Exception('Failed to load');
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getData();
  }


  Widget buildUserInfoBody() {
    return Container(
      margin: EdgeInsets.all(10),
      decoration: BoxDecoration(boxShadow: [
        BoxShadow(
          color: Colors.grey.withOpacity(0.5),
          spreadRadius: 3,
          blurRadius: 7,
          offset: Offset(0, 3), // changes position of shadow
        ),
      ], color: Colors.white, borderRadius: BorderRadius.circular((20))),
      child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            buildUserBar(),
            buildInfoBody(),
          ]),
    );
  }

  Widget buildAppBar() {
    return Container(
      decoration: BoxDecoration(
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.5),
            spreadRadius: 3,
            blurRadius: 7,
            offset: Offset(0, 3), // changes position of shadow
          ),
        ],
        color: Colors.white,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          IconButton(
              onPressed: () {
                Navigator.pop(context);
              },
              icon: Icon(Icons.arrow_back)),
          Container(
            child: Row(
              children: [Icon(Icons.abc), Text("$belong")],
            ),
          ),
          IconButton(onPressed: () {}, icon: Icon(Icons.more_horiz)),
        ],
      ),
    );
  }

  Widget buildUserBar() {
    return Container(
      margin: EdgeInsets.fromLTRB(10, 10, 10, 0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Card(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadiusDirectional.circular(10)),
                clipBehavior: Clip.antiAlias,
                child: Image.network(
                  'https://images.pexels.com/photos/850359/pexels-photo-850359.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=375',
                  width: 40,
                  height: 40,
                  fit: BoxFit.cover,
                ),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Text(
                    "$userName",
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Text("data")
                ],
              ),
            ],
          ),
          TextButton(
              onPressed: () {},
              child: Text(
                "关注",
                style: TextStyle(
                  color: Colors.black,
                  fontWeight: FontWeight.bold,
                ),
              ))
        ],
      ),
    );
  }

  Widget buildInfoBody() {
    return Container(
      margin: EdgeInsets.all(10),
      height: 100,
      child: ListView(
        // mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            // mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                "$title",
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
              SizedBox(
                height: 10,
              ),
              Text(
                "$articleContext",
                softWrap: true,
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget buildImgList() {
    return Container();
  }

  Widget buildCommentList() {
    return Container(
      margin: EdgeInsets.all(10),
      height: 500,
      decoration: BoxDecoration(boxShadow: [
        BoxShadow(
          color: Colors.grey.withOpacity(0.5),
          spreadRadius: 3,
          blurRadius: 7,
          offset: Offset(0, 3), // changes position of shadow
        ),
      ], color: Colors.white, borderRadius: BorderRadius.circular((20))),
      child: ListView.builder(
          itemCount: commentList.length,
          itemBuilder: (context, index) {
            Map<String, dynamic> comment = commentList[index];
            return buildCommentItem(context, comment);
          }),
    );
  }

  Widget buildBottomComment() {
    return Container(
      height: MediaQuery.of(context).size.height * 0.1,
      padding: EdgeInsets.symmetric(horizontal: 16.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Container(
            width: MediaQuery.of(context).size.width * 0.8,
            child: TextField(
              controller: _controller,
              decoration: InputDecoration(
                hintText: 'Type something here...',
              ),
            ),
          ),
          Expanded(
              // width: MediaQuery.of(context).size.width * 0.2,
              // height: MediaQuery.of(context).size.height * 0.05,
              child: IconButton(
                  onPressed: () {
                    createComment();
                  },
                  icon: Icon(Icons.send)))
        ],
      ),
      // IconButton(onPressed: () {}, icon: Icon(Icons.send))
    );
  }

  Future<void> createComment() async {
    try {
      String articleComment = _controller.text;
      final response = await http.post(
          Uri.parse(
              "http://$host/articleComment/create_comment?ArticleId=$articleId&Context=$articleComment"),
          headers: {
            "Authorization": UserModel.token
          }).timeout(const Duration(seconds: 30));
      if (response.statusCode == 200) {
        if (json.decode(response.body)["code"] == 200) {
          _controller.clear();
          getData();
        } else {
          ShowDialog(json.decode(response.body)['res']);
        }
      }
    } catch (e) {
      print(e);
      throw Exception('Failed to load');
    }
  }

  Widget buildCommentItem(BuildContext context, Map<String, dynamic> comment) {
    return Container(
      padding: EdgeInsets.all(10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Card(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadiusDirectional.circular(10)),
                clipBehavior: Clip.antiAlias,
                child: Image.network(
                  'https://images.pexels.com/photos/850359/pexels-photo-850359.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=375',
                  width: 40,
                  height: 40,
                  fit: BoxFit.cover,
                ),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("${comment["user_id"]}"),
                  Text("${comment["context"]}"),
                  Text("${comment["create_time"]}"),
                ],
              ),
            ],
          ),
          IconButton(onPressed: () {}, icon: Icon(Icons.more_horiz))
        ],
      ),
    );
  }
}
